package com.shenglue.ssi.dao;

import java.util.List;

import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import com.shenglue.ssi.domain.Good;

public class GoodDaoImpl extends SqlMapClientDaoSupport implements GoodDao {

	/**
	 * 查询所有商品信息
	 */
	public List<Good> selectAllGood() {
		@SuppressWarnings("unchecked")
		List<Good> list = this.getSqlMapClientTemplate().queryForList(
		"selectAllGood");

		if (list != null && list.size() > 0) {
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 按条件查询 商品信息
	 */
	public List<Good> selectGoodByCond( Good product ){
		@SuppressWarnings("unchecked")
		List<Good> list = this.getSqlMapClientTemplate().queryForList(
		"selectGoodByCond", product);

		if (list != null && list.size() > 0) {
			return list;
		} else {
			return null;
		}
	}

	/**
	 * 增加商品记录
	 */
	public boolean saveGood(Good good) {

		try {
			Object oRtn = this.getSqlMapClientTemplate().insert( "insertGood", good );
			// 已改正 来自网上的写法。已有文章讨论

			//插入成功 返回true
			return true;
		}
		catch ( DataAccessException e ) {
			//失败 返回false
			return false;
		}
	}

	/**
	 * 删除商品记录
	 */
	public boolean deleteGood(int goodId) {
		int flag = this.getSqlMapClientTemplate().delete( "deleteGoodById", goodId );
		if( flag > 0 ) {
			return true;
		}
		return false;
	}

	/**
	 * 修改商品记录
	 */
	public boolean updateGood(Good good) {

		int flag = this.getSqlMapClientTemplate().update("updateGood", good);
		if( flag > 0 ) {
			return true;
		}else{
			return false;
		}
	}

	/**
	 * 为修改，根据 Id 查一条 商品记录
	 */
	public Good getOneGoodForUpdate( int goodId ) {
		Object oGood = this.getSqlMapClientTemplate().
		queryForObject( "getOneGoodForUpdate", goodId );

		Good good = (Good)oGood;

		return good;

	}

	/**
	 * 查询 某供应商的所有商品信息
	 */
	public List<Good> selectGoodOf1Supp( int suppId ) {
		@SuppressWarnings("unchecked")
		List<Good> list = this.getSqlMapClientTemplate().queryForList(
		"selectGoodOf1Supp", suppId );

		if ( list != null && list.size() > 0 ) {
			return list;
		} else {
			return null;
		}
	}
}
